﻿using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;
using System.IO;

namespace TileMaker
{
    partial class MainWindow
    {
        private Stopwatch sw;

        public void InitPicBox()
        {
            this.PicBox.LoadProgressChanged += new ProgressChangedEventHandler(PicBox_LoadProgressChanged);
            this.PicBox.LoadCompleted += new AsyncCompletedEventHandler(PicBox_LoadCompleted);

            sw = new Stopwatch();
        }

        public void PicLoad(string file)
        {
            sw.Start();
            PicBox.LoadAsync(file);
            ProgBar.Visible = true;
            FileName = file;
        }

        void PicBox_LoadProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            ProgBar.Value = e.ProgressPercentage;
            ImgInfos.Text = String.Format("Elapsed {0:00}:{1:00}:{2:000} | Loading {3:00}%", Math.Truncate(sw.Elapsed.TotalMinutes), sw.Elapsed.Seconds, sw.Elapsed.Milliseconds,
                                                                                                e.ProgressPercentage);
        }


        void PicBox_LoadCompleted(object sender, AsyncCompletedEventArgs e)
        {
            ProgBar.Visible = false;
            ProgBar.Value = 0;
            

            if (e.Cancelled) { ImgInfos.Text = "Image loading cancelled."; sw.Stop(); return; }
            if (e.Error != null)
            {
                sw.Stop();
                MessageBox.Show("Error during loading image:\n" + e.Error.Message, e.Error.Source + " error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            ImgInfos.Text = String.Format("Elapsed {0:00}:{1:00}:{2:000} | Getting optimal witdh ...", Math.Truncate(sw.Elapsed.TotalMinutes), sw.Elapsed.Seconds, sw.Elapsed.Milliseconds);
            Application.DoEvents();
            OptimalWidth = PicBox.Image.Width;
            while (true)
            {
                if (Miscallenous.DividibleBy512((ulong)OptimalWidth)) break;
                OptimalWidth++;
            }

            ImgInfos.Text = String.Format("Elapsed {0:00}:{1:00}:{2:000} | Getting optimal height ...", Math.Truncate(sw.Elapsed.TotalMinutes), sw.Elapsed.Seconds, sw.Elapsed.Milliseconds);
            Application.DoEvents();
            OptimalHeight = PicBox.Image.Height;
            while (true)
            {
                if (Miscallenous.DividibleBy512((ulong)OptimalHeight)) break;
                OptimalHeight++;
            }

            //using (Graphics g = Graphics.FromImage(PicBox.Image))
            //{
            //    Rectangle Cent = Center((Bitmap)PicBox.Image, OptimalWidth, OptimalHeight);
            //    Color col = Color.FromArgb(50, Color.Green);
            //    SolidBrush brush = new SolidBrush(col);
            //    g.FillRectangle(brush, Cent);
            //}

            int WidthTiles = (int)Math.Truncate((float)OptimalWidth / 512.0f);
            int HeightTiles = (int)Math.Truncate((float)OptimalHeight / 512.0f);

            sw.Stop();

            ImgInfos.Text = String.Format("Loading time: {0:00}:{1:00}:{2:000} | Dimensions {3}x{4} | Cropped Dimensions: {5}x{6} | Format: {7} | Maximum 512px tiles: {8}", Math.Truncate(sw.Elapsed.TotalMinutes), sw.Elapsed.Seconds, sw.Elapsed.Milliseconds,
                                                                                                                                    PicBox.Image.Width, PicBox.Image.Height,
                                                                                                                                    OptimalWidth, OptimalHeight,
                                                                                                                                    Miscallenous.PixelFormatFancy(PicBox.Image.PixelFormat), WidthTiles * HeightTiles);
            CalcTiles.Enabled = true;
            InfoTiles.Visible = true;

            if (File.Exists(Path.ChangeExtension(PicBox.ImageLocation, "gps")))
            {
                foreach (string line in File.ReadAllLines(Path.ChangeExtension(PicBox.ImageLocation, "gps")))
                {
                    string[] content = line.Split('=');
                    switch (content[0].Trim())
                    {
                        case "TLlat":
                            TLlat.Text = content[1].Trim();
                            break;
                        case "TLlong":
                            TLlong.Text = content[1].Trim();
                            break;
                        case "BRlat":
                            BRlat.Text = content[1].Trim();
                            break;
                        case "BRlong":
                            BRlong.Text = content[1].Trim();
                            break;
                        default:
                            break;
                    }
                }
                CalcTiles_Click(null, EventArgs.Empty);
            }
        }

        Rectangle Center(Bitmap Input, int Width, int Height)
        {
            GraphicsUnit gu = GraphicsUnit.Pixel;
            RectangleF r = Input.GetBounds(ref gu);
            Point Cent = new Point((int)(r.Left + r.Right) / 2, (int)(r.Top + r.Bottom) / 2);
            
            int dH = Math.Abs(Input.Height - Height);
            int dW = Math.Abs(Input.Width - Width);

            return new Rectangle(Cent.X-(Width/2), Cent.Y-(Height/2), Width, Height);
        }

        Bitmap Crop(Bitmap Input, Rectangle r)
        {
            Bitmap nb = new Bitmap(r.Width, r.Height);
            nb.SetResolution(Input.HorizontalResolution, Input.VerticalResolution);
            Graphics g = Graphics.FromImage(nb);
            g.DrawImage(Input, -r.X, -r.Y);
            return nb;
        }

        Bitmap CropCentered(Bitmap Input, int Width, int Height)
        {
            return Crop(Input, Center(Input, Width, Height));
        }
    }
}